var $ = window.$;
var jade = require('jade');
var config = require('../../../core/config');
var event = require('../../../core/event');
var uiUtil = require('../../../util/ui');
var util = require('../../../util/index');
var animate = require('../../../util/animate');
var fs = require('fs');
var path = require('path');
var note = require("../manager.js");
var notify = require('../../notify/ui');
var exec = require('child_process').execFile;
var io = require('../../io/ui');

var _inited = false;

var ret = {
    init: function() {
        if (_inited) {
            return;
        }
        this.allowedExt = {"mc":true, "mce":true, "bmp": true, "jpg":true, "jpeg":true, "png":true, "wav":true, "ogg":true, "mp3":true};
        event.bind(event.events.file.exportMcz, 'export_mcz', this);
        event.bind(event.events.key.up, 'export_mcz', this);
        event.lock('key', 'export_mcz');
        _inited = true;
    },

    onEvent : function(e, param){
        if(e == event.events.file.exportMcz){
            this.show();
            return true;
        }
        if(param.key == 27){
            this.hide();
            return event.result.stopAll;
        }
    },


    bindUIEvent : function(){
        var self = this;
        this.parent.on('click','.g_click', function() {
            var type = $(this).data('type');
            if (type == 'close') {
                self.hide();
                return;
            }else if(type == "export"){
                self.packageSelected();
                return;
            }
        });

        this.parent.on('click','.g_barhead i', function () {
            self.hide();
        });
        
        this.fileList.on('click', 'li', function(e) {
            $(this).toggleClass('curr');
        });
    },

    //只支持windows <_<
    packageSelected : function(){
        var files = this.fileList.children(".curr");
        if(files.length == 0){
            return;
        }
        io.getSavePath().then(function(name){
            if(!name){
                return;
            }
            name = util.ensureSuffix(name, 'mcz');
            //-j参数忽略路径
            var cmd = util.getPath("node_modules") + "/zip.exe";
            var args = ["-j"];
            var mapDir = note.getFilePath('/');
            args.push(name);
            for(var i=0;i<files.length;i++){
                var fn = $(files[i]).text();
                args.push(mapDir + "/" + fn);
            }
            notify.showWaiting(true);
            exec(cmd, args, {cwd : mapDir}, function (error, stdout, stderr) {
                if (error !== null) {
                    notify.addNotify({msg : stderr });
                    notify.showWaiting(false);
                    return;
                }
                notify.addNotify({msg : name + config.i18n("mcz09") });
                notify.showWaiting(false);
            });
        });

    },

    initFileList : function(){
        var self = this;

        var dir = note.getFilePath('/');
        fs.readdir(dir, function(err, files) {
            var lst = "";
            for (var i = 0; i < files.length; i++) {
                var file = path.join(dir, files[i]);
                var stat = fs.statSync(file);
                if (!stat.isDirectory()) {
                    var file = files[i];
                    var n = file.lastIndexOf(".");
                    var ext = file.substring(n + 1).toLowerCase();
                    if (self.allowedExt[ext]) {
                        lst += '<li class="curr" ext="' + ext + '">' + file + '</li>';
                    }
                }
            }
            self.fileList.html(lst);
        });
    },

    show : function(){
        if(this.parent){
            return;
        }
        var tmpl = jade.compileFile('./tmpl/note/export.jade');
        var html = tmpl({config: config});
        $('#dialog_layer').append(html);
        this.parent = $('#dialog_export_mcz');
        this.parent.show();
        uiUtil.dialogInc();
        var self = this;
        animate.normalScaleIn(this.parent).then(function() {
            self.fileList = self.parent.find(".file_list").children("ul");
            self.bindUIEvent();
            self.initFileList();
        });
    },


    hide : function(){
        var self = this;
        animate.normalScaleOut(this.parent).then(function(){
            self.parent.remove();
            self.parent = null;
            uiUtil.dialogDec();
        });
        event.unlock();
        _inited = false;
    }
};



module.exports = ret;